import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'dva'
import {Avatar, Button, Form, Modal, Table} from 'antd'
import moment from 'moment'


class ProductModal extends React.Component {

  componentWillMount () {
    const {dispatch} = this.props
    dispatch({
      type: 'goods/query',
    })
  }

  render () {
    const {
      handleSelect,
      item = {},
      onOk,
      loading,
      dispatch,
      goods,
      form: {
        getFieldDecorator,
        validateFields,
        getFieldsValue,
      },
      ...modalProps
    } = this.props
    const {list = [], pagination = {}} = goods
    const handleOk = () => {
      validateFields((errors) => {
        if (errors) {
          return
        }
        const data = {
          ...getFieldsValue(),
          key: item.key,
        }
        if (data.birthDay) {
          data.birthDay = moment(data.birthDay).format('YYYY-MM-DD')
        }
        onOk(data)
      })
    }

    const modalOpts = {
      ...modalProps,
      onOk: handleOk,
    }

    const listProps = {
      rowKey: 'id',
      dataSource: list,
      loading: loading.effects['goods/query'],
      pagination,
      location,
      onChange (page) {
        dispatch({
          type: 'goods/query',
          payload: {
            current: page.current,
            size: page.size,
          },
        })
      },
    }

    const columns = [
      {
        title: '商品编号',
        dataIndex: 'sn',
        key: 'sn',
      }, {
        title: '商品图片',
        dataIndex: 'goodsImg',
        key: 'goodsImg',
        render: val => {
          return val ? <Avatar src={val} size="large"/> : '暂无图片'
        },
      }, {
        title: '商品名称',
        dataIndex: 'goodsName',
        key: 'goodsName',
      }, {
        title: '库存数量',
        dataIndex: 'stockNum',
        key: 'stockNum',
      }, {
        title: '品牌',
        dataIndex: 'brandName',
        key: 'brandName',
      }, {
        title: '价格(RMB)',
        dataIndex: 'salePrice',
        key: 'salePrice',
      }, {
        title: '折扣',
        dataIndex: 'discount',
        key: 'discount',
      },
      {
        title: '所属仓库',
        dataIndex: 'depotName',
        key: 'depotName',
      }, {
        title: '操作',
        key: 'operation',
        width: 100,
        render: (_, record) => <Button onClick={() => handleSelect(record)} type={'primary'}>选择商品</Button>,
      },
    ]

    return (
      <Modal {...modalOpts}>
        <Table
          {...listProps}
          scroll={{x: 800}}
          columns={columns}
          simple
          rowKey={record => record.id}
        />
      </Modal>
    )
  }
}

ProductModal.propTypes = {
  form: PropTypes.object.isRequired,
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default connect(({loading, goods}) => ({loading, goods}))(Form.create()(ProductModal))
